import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  login as loginAPI, 
  logout as logoutAPI, 
  getUserProfile, 
  validateToken,
  type LoginParams,
  type LoginResponse 
} from '@renderer/api/login'

// 用户信息类型定义
export interface UserInfo {
  id: string
  name: string
  userType: 'super_admin' | 'manager' | 'worker'
  avatar: string
  permissions: string[]
  shopId?: string
  shopName?: string
  workerId?: string
  managerId?: string
  loginTime?: string
  onlineDuration?: number
  workerStatus?: string
}

// 认证状态Store
export const useAuthStore = defineStore('auth', () => {
  // 响应式状态
  const isLoggedIn = ref<boolean>(false)
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string | null>(null)
  const refreshToken = ref<string | null>(null)
  const permissions = ref<string[]>([])
  const isLoading = ref<boolean>(false)

  // 计算属性
  const userType = computed(() => userInfo.value?.userType || null)
  const userName = computed(() => userInfo.value?.name || '')
  const userAvatar = computed(() => userInfo.value?.avatar || '')
  const shopName = computed(() => userInfo.value?.shopName || '')
  
  // 权限检查计算属性
  const isSuperAdmin = computed(() => userType.value === 'super_admin')
  const isManager = computed(() => userType.value === 'manager')
  const isWorker = computed(() => userType.value === 'worker')
  
  // 获取重定向路径
  const getRedirectPath = computed(() => {
    switch (userType.value) {
      case 'super_admin':
        return '/admin/dashboard'
      case 'manager':
        return '/manager/dashboard'
      case 'worker':
        return '/worker/orders'
      default:
        return '/login'
    }
  })

  // 从本地存储初始化状态
  const initializeAuth = () => {
    try {
      const savedToken = localStorage.getItem('accessToken')
      const savedRefreshToken = localStorage.getItem('refreshToken')
      const savedUserInfo = localStorage.getItem('userInfo')

      if (savedToken && savedUserInfo) {
        token.value = savedToken
        refreshToken.value = savedRefreshToken
        userInfo.value = JSON.parse(savedUserInfo)
        permissions.value = userInfo.value?.permissions || []
        isLoggedIn.value = true

        console.log('从本地存储恢复用户状态:', {
          userType: userInfo.value?.userType,
          name: userInfo.value?.name,
          permissions: permissions.value.length
        })
      }
    } catch (error) {
      console.error('初始化认证状态失败:', error)
      clearAuthData()
    }
  }

  // 清除认证数据
  const clearAuthData = () => {
    isLoggedIn.value = false
    userInfo.value = null
    token.value = null
    refreshToken.value = null
    permissions.value = []
    
    localStorage.removeItem('accessToken')
    localStorage.removeItem('refreshToken')
    localStorage.removeItem('userInfo')
  }

  // 保存认证数据
  const saveAuthData = (authData: LoginResponse) => {
    const { token: accessToken, refreshToken: newRefreshToken, user } = authData

    token.value = accessToken
    refreshToken.value = newRefreshToken
    userInfo.value = user
    permissions.value = user.permissions || []
    isLoggedIn.value = true

    // 保存到本地存储
    localStorage.setItem('accessToken', accessToken)
    localStorage.setItem('refreshToken', newRefreshToken)
    localStorage.setItem('userInfo', JSON.stringify(user))

    console.log('认证数据已保存:', {
      userType: user.userType,
      name: user.name,
      shopId: user.shopId,
      permissions: user.permissions?.length || 0
    })
  }

  // 登录操作
  const login = async (loginParams: LoginParams): Promise<string> => {
    try {
      isLoading.value = true
      console.log('执行登录请求:', { username: loginParams.username })

      const response = await loginAPI(loginParams)
      // 兼容后端响应格式：{success: true, data: {token, tokenType, userInfo}}
      const backendData = response.data.data
      
      // 转换为前端期望的格式
      const authData: LoginResponse = {
        token: backendData.token,
        refreshToken: backendData.token, // 如果后端没有单独的refreshToken，使用同一个token
        user: {
          id: backendData.userInfo.id || '1',
          name: backendData.userInfo.username || backendData.userInfo.realName || 'Admin',
          userType: backendData.userInfo.role || 'super_admin',
          avatar: backendData.userInfo.avatar || '',
          permissions: backendData.userInfo.permissions || ['*:*:*'], // 超级管理员拥有所有权限
          shopId: backendData.userInfo.shopId,
          shopName: backendData.userInfo.shopName
        }
      }

      // 保存认证数据
      saveAuthData(authData)

      // 返回重定向路径
      return authData.redirectPath || getRedirectPath.value

    } catch (error: any) {
      console.error('登录失败:', error)
      clearAuthData()
      
      let errorMessage = '登录失败，请检查用户名和密码'
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message
      } else if (error.message) {
        errorMessage = error.message
      }
      
      throw new Error(errorMessage)
    } finally {
      isLoading.value = false
    }
  }

  // 登出操作
  const logout = async (showMessage: boolean = true): Promise<void> => {
    try {
      isLoading.value = true

      // 调用后端登出接口
      if (token.value) {
        await logoutAPI()
      }

      if (showMessage) {
        ElMessage.success('已安全退出登录')
      }

    } catch (error) {
      console.error('登出请求失败:', error)
      // 即使后端登出失败，也要清除本地数据
    } finally {
      clearAuthData()
      isLoading.value = false
    }
  }

  // 刷新用户信息
  const refreshUserInfo = async (): Promise<void> => {
    try {
      if (!token.value) {
        throw new Error('未登录')
      }

      const response = await getUserProfile()
      const userData = response.data.data.user

      userInfo.value = userData
      permissions.value = userData.permissions || []
      
      // 更新本地存储
      localStorage.setItem('userInfo', JSON.stringify(userData))

      console.log('用户信息已刷新:', userData)

    } catch (error) {
      console.error('刷新用户信息失败:', error)
      throw error
    }
  }

  // 验证Token有效性
  const checkTokenValidity = async (): Promise<boolean> => {
    try {
      if (!token.value) {
        return false
      }

      await validateToken()
      return true

    } catch (error) {
      console.error('Token验证失败:', error)
      clearAuthData()
      return false
    }
  }

  // 权限检查方法
  const hasPermission = (permission: string): boolean => {
    if (isSuperAdmin.value) {
      return true // 超级管理员拥有所有权限
    }
    return permissions.value.includes(permission)
  }

  // 批量权限检查
  const hasAnyPermission = (permissionList: string[]): boolean => {
    if (isSuperAdmin.value) {
      return true
    }
    return permissionList.some(permission => permissions.value.includes(permission))
  }

  // 检查是否有所有权限
  const hasAllPermissions = (permissionList: string[]): boolean => {
    if (isSuperAdmin.value) {
      return true
    }
    return permissionList.every(permission => permissions.value.includes(permission))
  }

  // 角色权限检查
  const canAccessRoute = (routePermission?: string | string[]): boolean => {
    if (!isLoggedIn.value) {
      return false
    }

    if (!routePermission) {
      return true // 无权限要求的路由
    }

    if (Array.isArray(routePermission)) {
      return hasAnyPermission(routePermission)
    } else {
      return hasPermission(routePermission)
    }
  }

  // 获取用户显示信息
  const getUserDisplayInfo = computed(() => {
    if (!userInfo.value) {
      return {
        name: '未登录',
        type: '游客',
        avatar: '',
        shop: ''
      }
    }

    const typeMap = {
      'super_admin': '超级管理员',
      'manager': '店长',
      'worker': '打手'
    }

    return {
      name: userInfo.value.name,
      type: typeMap[userInfo.value.userType] || '未知',
      avatar: userInfo.value.avatar || '',
      shop: userInfo.value.shopName || ''
    }
  })

  // 自动登录检查
  const autoLogin = async (): Promise<boolean> => {
    try {
      if (!token.value) {
        return false
      }

      const isValid = await checkTokenValidity()
      if (isValid && userInfo.value) {
        console.log('自动登录成功:', userInfo.value.name)
        return true
      }

      return false
    } catch (error) {
      console.error('自动登录失败:', error)
      return false
    }
  }

  // 暴露状态和方法
  return {
    // 状态
    isLoggedIn,
    userInfo,
    token,
    refreshToken,
    permissions,
    isLoading,

    // 计算属性
    userType,
    userName,
    userAvatar,
    shopName,
    isSuperAdmin,
    isManager,
    isWorker,
    getRedirectPath,
    getUserDisplayInfo,

    // 方法
    initializeAuth,
    login,
    logout,
    refreshUserInfo,
    checkTokenValidity,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    canAccessRoute,
    autoLogin,
    clearAuthData
  }
})